define([
        'app/utils/WebUtils',
        'app/service/GeneralServices',
        'underscore',
        'app/utils/AMUIPaginationUtils',
        'app/utils/TimerUtils',
        'app/utils/UploadPPTUtils',
        'app/utils/WebSocketUtils',
        'app/utils/AMUICookieUtils',
        'app/utils/CommonUtils'
        
        
        ], function (
        WebUtils,
        gs,
        _,
        AMUIPaginationUtils,
        TimerUtils,
        UploadPPTUtils,
        WebSocketUtils,
        AMUICookieUtils
        
    ) {
	
	var opt ={};
	var p1 = {};
	var win = window;
	opt = AMUICookieUtils.initializePage();
	p1 = AMUICookieUtils.initializePage();
	
	p1.s=$.getUrlParam("s");
	p1.p=$.getUrlParam("p");
	p1.w=$.unicodeToHanzi($.getUrlParam("w"));
	p1.c=$.getUrlParam("c"); //cataloguuid
	
	opt.s=$.getUrlParam("s");
	opt.p=$.getUrlParam("p");
	opt.w=$.unicodeToHanzi($.getUrlParam("w"));
	opt.c = $.getUrlParam("c"); //cataloguuid
	
	console.log(opt);
	$("#wjt_search_input").val(p1.w);
	
	
	function index_urlSearch (w,p,c,s){
		if($.isNullStr(c)){
			c = "";
		}
		if($.isNull(s)){
    		s = $.paginationDefaultSize;
    	}
    	location.search="?w="+$.toUnicode(w)+"&p="+p+"&s="+s+"&c="+c;
	}
	
	
	gs.wjt_admin_init(p1, function(resp){
		if(resp.status == "500"){
			WebUtils.alert("连接错误，请刷新页面重试！");	
			return;
		}
		
		opt.navi_main = "我的微讲堂";
		opt.navi_sub = "创建你的知识微讲堂"
		
		opt.copyrighttext = resp.result.admin_copyright;//"© 2016 版权所有 中研沃兮网络科技（上海）有限公司";
		WebUtils.inputInt($("#wjt-admin-copyright"), opt.copyrighttext);
		
		WebUtils.adminPageInt(opt);
		
		$(".wjt-admin-list").html("");
		
		for(var i = 0; i < resp.result.rooms.length; i++){
			var item = resp.result.rooms[i];
			var _pwd = "无";
			if(!$.isNullStr(item.pwd)){
				_pwd = item.pwd;
			}
			var roomstatusdiv = ""
			var roomlivetypediv = "";
			var pptlivetypediv = "";
			var pptandvideodiv = "";
			var roomlivestartdiv = "";
			
			if(item.type == "3"){
				roomstatusdiv = "<span class=\"am-badge am-badge-success\">回顾</span>"
			}else if(item.type == "1"){
				var now = (new Date()).getTime();
				if(item.time > now){
					roomstatusdiv = "<span class=\"am-badge am-badge-secondary\">预告</span>"	
				}else{
					
					if(now > item.endtime){
						roomstatusdiv = "<span class=\"am-badge am-badge-success\">回顾</span>"						
					}else{
						roomstatusdiv = "<span class=\"am-badge am-badge-warning\">直播</span>"
					}

				}
			}
			
			
			if(item.liveType == "1"){
				roomlivetypediv = "视频直播";
				roomlivestartdiv = '<a style="background-color:#3bb4f2;color:white;" class="am-btn am-btn-succes am-round am-btn-xs" href="admin-videolive.html?roomuuid='+item.uuid+'">开始直播</a>';
				pptlivetypediv = '<li style="text-align: left;"><a class="continuestreamingbtn" data-roomuuid="'+item.uuid+'" href="javascript:void(0)"><span style="margin-right:10px;" class="am-icon-check"></span>继续直播</a></li>';
				//pptlivetypediv = '<li><a href="admin-videolive.html?roomuuid='+item.uuid+'">直播功能</a></li>';
			}else if(item.liveType == "2"){
				roomlivetypediv = "PPT直播";
				pptandvideodiv = '<li><a href="admin-roomdetails.html?roomuuid='+item.uuid+'&tab=3">编辑幻灯片</a></li>';
				pptlivetypediv = '<li style="text-align: left;"><a class="continuestreamingbtn" data-roomuuid="'+item.uuid+'" href="javascript:void(0)"><span style="margin-right:10px;" class="am-icon-check"></span>继续直播</a></li>';
				//pptlivetypediv = '<li><a href="admin-videolive.html?roomuuid='+item.uuid+'">直播功能</a></li>';
				roomlivestartdiv = '';//'<a style="background-color:#5eb95e;color:white;" class="am-btn am-btn-succes am-round am-btn-xs" href="admin-videolive.html?roomuuid='+item.uuid+'">开始直播</a>';
			}
			var didAllowDiscussing = "";
			if(item.type == "3"){
				didAllowDiscussing = '<span class="am-badge am-badge-danger">已禁言</span>';
			}else{
				didAllowDiscussing = '<span class="am-badge am-badge-success">不禁言</span>';
			}
			/*
			var el = $(
					'<tr>'+
		            '<td><span class="wjt-am-popover" data-am-popover="{content: \''+item.name+'\', trigger: \'hover focus\'}">'+$.shortForStr(item.name,20)+'</span></td>'+
		            '<td>'+$.timeFormat1(item.time)+'</td> '+
		            '<td>'+roomlivetypediv+'</td> '+
		            '<td><span class="am-badge am-badge-secondary">'+item.attendeecount+'人</span></td>'+
		            '<td>'+
		            	'<span class="am-badge am-badge-danger">'+
		            		_pwd+
						'</span>'+
					  '</td>'+
		            '<td>'+
		              '<div class="am-dropdown" data-am-dropdown="">'+
		                '<button class="am-btn am-btn-default am-btn-xs am-dropdown-toggle" data-am-dropdown-toggle=""><span class="am-icon-cog"></span> <span class="am-icon-caret-down"></span></button>'+
		                '<ul class="am-dropdown-content">'+
//						  '<li><a href="#">主持人入口</a></li>'+
		                  pptlivetypediv +
		                  '<li><a href="admin-roomdetails.html?roomuuid='+item.uuid+'">编辑／完善信息</a></li>'+
		                  '<li><a href="admin-roomdetails.html?roomuuid='+item.uuid+'&tab=2">设置Logo与封面</a></li>'+
		                  pptandvideodiv+
		                  '<li><a href="admin-roomdetails.html?roomuuid='+item.uuid+'&tab=5">设置访问密码</a></li>'+
//		                  '<li><a href="#">生成微信二维码</a></li>'+
//		                  '<li><a href="admin-chairinvite.html?roomuuid='+item.uuid+'">设置主讲嘉宾</a></li>'+
//		                  '<li><a href="#">主持人管理</a></li>'+
//		                  '<li><a href="#">禁言设置：'+didAllowDiscussing+'</a></li>'+
		                  '<li><a href="javascript:void(0)" class="wjt-room-del" data-roomname="'+item.name+'" data-roomuuid="'+item.uuid+'">彻底删除</a></li>'+
		                '</ul>'+
		              '</div>'+
		            '</td>'+
		          '</tr>');
		          
		          */
			
			var el = $(
					'<tr>'+
		            '<td><span class="wjt-am-popover" data-am-popover="{content: \''+item.name+'\', trigger: \'hover focus\'}">'+$.shortForStr(item.name,20)+'</span></td>'+
		            '<td>'+roomstatusdiv+'</td> '+
		            '<td>'+$.timeFormat1(item.time)+'</td> '+
		            '<td>'+roomlivetypediv+'</td> '+
		            '<td><span class="am-badge am-badge-secondary">'+item.attendeecount+'人</span></td>'+
		            '<td>'+
		            	'<span class="am-badge am-badge-danger">'+
		            		_pwd+
						'</span>'+
					  '</td>'+
		            '<td>'+
		              '<div class="am-dropdown" data-am-dropdown="">'+
		                '<button class="am-btn am-btn-default am-btn-xs am-dropdown-toggle" data-am-dropdown-toggle=""><span class="am-icon-cog"></span> <span class="am-icon-caret-down"></span></button>'+
		                '<ul class="am-dropdown-content">'+
		                  pptlivetypediv +
		                  '<li style="text-align: left;"><a href="admin-roomdetails.html?roomuuid='+item.uuid+'"><span style="margin-right:10px;" class="am-icon-pencil-square-o"></span>修改信息</a></li>'+
		                  '<li style="text-align: left;"><a href="admin-roomdetails.html?roomuuid='+item.uuid+'&tab=4"><span style="margin-right:10px;" class="am-icon-lock"></span>访问密码</a></li>'+
		                  '<li style="text-align: left;"><a href="javascript:void(0)" class="wjt-room-del" data-roomname="'+item.name+'" data-roomuuid="'+item.uuid+'"><span style="margin-right:10px;" class="am-icon-th"></span>彻底删除</a></li>'+
		                '</ul>'+
		              '</div>'+
		            '</td>'+
		          '</tr>');
		          
			$(".wjt-admin-list").append(el);
		}

		try{
			cefObject.call("devicedetect","");	
		}catch(err){
			
		}
		//微讲堂列表
		var catalogs = resp.result.catalogs;
		if(typeof(catalogs.length) !="undefined"){
			if(catalogs.length > 1){
				//$("#wjt_room_catalog").append("<option value=\"\">全部</option>");
				for(var i = 2; i < catalogs.length; i++){
					var option_item = "<option value=\""+catalogs[i].uuid+"\">"+catalogs[i].name+"</option>";
					$("#wjt_room_catalog").append(option_item);	
				}
			}
			
			$("#wjt_room_catalog").data("init","1");
			$("#wjt_room_catalog").val(opt.c);
			
		}else{
			$(".wjt_room_catalog_container").hide();
		}
		
		//下拉栏
		$('.am-dropdown').dropdown();
		//弹出框
		$('.wjt-am-popover').popover();
		
		//初始化pagination
		if(resp.result.total <= $.paginationDefaultSize){
			var page_total = 1;	
		}else{
			var page_total = parseInt((resp.result.total-1)/$.paginationDefaultSize) + 1; 
		}
		AMUIPaginationUtils.init($(".wjt-pagination-container"), page_total, resp.result.current, 
			function(page){
				index_urlSearch($("#wjt_search_input").val(),page,opt.c);
			}
		);
		
		//继续直播
		$(".continuestreamingbtn").click(function(){
			var roomuuid = $(this).data("roomuuid");
			var useruuid = opt.useruuid;
			var cef_msg = {};
			cef_msg.useruuid = useruuid;
			cef_msg.roomuuid = roomuuid;
			try{
				cefObject.call("continuestream",JSON.stringify(cef_msg));	
			}catch(err){
				
			}

		});

		//delete
		$(".wjt-room-del").click(function(){
			var selected_roomuuid = $(this).data("roomuuid");
			var selected_roomname = $(this).data("roomname");
			var p ={
				roomuuid:selected_roomuuid,
				roomname:selected_roomname
			};
			
			WebUtils.confirm('是否删除此微讲堂【'+selected_roomname+'】，删除后将不能被恢复<input id="wjt_room_del_roomuuid_input" type="hidden" value="'+selected_roomuuid+'">',function(param){
				var input = $("#wjt_room_del_roomuuid_input").val();
				console.log(input);
				gs.wjt_delete_room({roomuuid:input},function(resp){
					$.refreshPage();
				});
			},function(){});
			
		});
		
	});
	
	
	$(".wjt-search-btn").click(function(){
		
		index_urlSearch($("#wjt_search_input").val(),1,opt.c);
		
	});
	
	
	$("#pptroomcreate").click(function(){
		/*
		var sec = 10;

		showCountDownTips(sec,function(){
			
		});
		*/
		try{
			cefObject.call("startpptlive",opt.useruuid);	
		}catch(err){
			
		}
		
	});
	
	function showCountDownTips(sec, finish_func){
		
		
		var t = sec * 1000;
		$("#uploadingcountdown").html(parseInt(t/1000));
		var t_i = 1000;
		
		$("#transingppt").modal();
		
		TimerUtils.startTimer(t_i,function(){
			t = t - t_i;
			$("#uploadingcountdown").html(parseInt(t/1000));
			if(t <= 0){
				TimerUtils.stopTimer();
				$("#transingppt").modal('close');
				finish_func();
			}
			
		})
	}
	
	$("#setlivedevice").click(function(){
		
		try{
			cefObject.call("devicesetting","");
		}catch(err){
			
		}
	});
	
	//
	$('#wjt_room_catalog').change(function(){
		
		
		var init = $("#wjt_room_catalog").data("init");
		
		if(init != "1"){
			var cataloguuid = $.val_trim($(this).val());
			opt.cataloguuid = cataloguuid;

			index_urlSearch($("#wjt_search_input").val(),"1", cataloguuid);
		}
		$("#wjt_room_catalog").data("init","0");
		

	});
	
	
	gs.luyan_ppt_server({},function(resp){
		
		if(resp.status == "200"){
			win.pptserver = resp.result.pptserver;
			win.callbackurl = resp.result.callbackurl;
			win.userid = opt.useruuid;
			
			/////////////////////
			var url = "basic/native/upload_ppt/folder/ppt";
			UploadPPTUtils.init("ppt_upload_container","upload_btn",url,
				function(up, file, info){
					var resp = JSON.parse(info.response);
					var filename = file.name;
					console.log(resp);
					if(resp.status != "201"){
						
						
						setTimeout(function(){
							WebUtils.alert("上传失败，请重试");	
							$("#uploading").modal('close');
						
						},2000);
			
					}

					filename = filename.replace(".pptx","");
					filename = filename.replace(".ppt","");

					var ftype = 'ppt';
					var temp_filename = filename.replace(".pdf",""); 
					if(temp_filename != filename){
						filename = temp_filename;
						ftype = 'pdf';
					}
					var key = resp.result.key
					var ppturl = win.pptserver + "ppt_to_jpg";
					var callbackurl = win.callbackurl.replace("{0}",win.userid);
					callbackurl = callbackurl.replace("{1}",key);

					var pptbody = {
						"key": key,
						"callbackurl": callbackurl,
						"pptname": encodeURI(filename),
						"type": ftype
					};
					console.log(pptbody);
					
					gs.luyan_ppt_trans(ppturl, pptbody, function(resp){
						
						$("#uploading").modal('close');
						
						var fsize = file.size/1000;//xxxkb
						fsize = parseInt(sec/1000);//xxxMB
						var sec = 6;
						if(fsize >= 3){
							sec = fsize *2;
						}
						showCountDownTips(sec,function(){
							location.reload();
						});
						
					});
					
				}
			);
			
			
		}		
		
	});
	
	
//	showCountDownTips(10);
	return {
		getUseruuid: function(){
			return opt.useruuid;
		}
	};
});